﻿using B.S.BaseData.Api.Write.Applicantion.Command.RBAC;
using B.S.BaseData.Api.Write.GetCelim;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Infrastructure.Interface;
using B.S.BataBase.Domain.RBAC;
using MediatR;
using Yitter.IdGenerator;

namespace B.S.BaseData.Api.Write.Applicantion.CommandHandler.RBAC
{
    public class UserAddCommandHandler : IRequestHandler<UserAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<UserModel> _userModel;
        private readonly IBaseRepository<UserRoleModel> _userroleModel;
        private readonly IIdContextCemil _idContextCemil;
        public UserAddCommandHandler(IBaseRepository<UserModel> userModel, IBaseRepository<UserRoleModel> userroleModel, IIdContextCemil idContextCemil)
        {
            _userModel = userModel;
            _userroleModel = userroleModel;
            _idContextCemil = idContextCemil;
        }
        public async Task<APIResult<int>> Handle(UserAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result=new APIResult<int>();
            var a = await _userModel.GetValues(x => x.UserName == request.UserName);
            if (a != null)
            {
                result.Code = ApiEnum.Success;
                result.Msg = "用户已存在";
                return await Task.FromResult(result);
            }
            UserModel model=new UserModel();
            model.Id=YitIdHelper.NextId();
            model.UserName= request.UserName;
            model.UserPwd= request.UserPwd;
            model.CreateName= _idContextCemil.UserName;
            model.IsDeleted = false;
            await _userModel.CreateAsync(model);

            foreach (var item in request.RoleIds)
            {
                UserRoleModel userRole = new UserRoleModel();
                userRole.Id=YitIdHelper.NextId();
                userRole.IsDeleted = true;
                userRole.UserId = model.Id;
                userRole.RoleId= item;
                userRole.CreateName = _idContextCemil.UserName;
                await _userroleModel.CreateAsync(userRole);
            }

            result.Code = ApiEnum.Success;
            result.Data = 1;
            result.Msg = "角色新增成功";
            return await Task.FromResult(result);
        }
    }
}
